package com.cdvtc.flower.web.servlet;

import com.cdvtc.flower.model.DataPoint;
import com.cdvtc.flower.util.DBUtil;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

@WebServlet("/PointServlet")
public class PointServlet extends HttpServlet {

    private ObjectMapper objectMapper = new ObjectMapper(); // 创建ObjectMapper实例

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<String> labels = new ArrayList<>();
        List<Integer> data = new ArrayList<>();
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement("SELECT p.product_name, SUM(od.quantity) AS total_quantity " +
                     "FROM products p " +
                     "JOIN orderdetails od ON p.product_id = od.product_id " +
                     "JOIN `order` o ON od.order_id = o.order_id " +
                     "WHERE o" +
                     ".review = '一般'" +
                     "GROUP BY p.product_id, p.product_name")) {
            ResultSet rs = pstmt.executeQuery();
            while (rs.next()) {
                String label = rs.getString("product_name");
                int value = rs.getInt("total_quantity");
                labels.add(label);
                data.add(value);
                System.out.println(label);
                System.out.println(value);
            }

            // 创建一个与前端期望的JSON格式相匹配的Data对象
            Map<String, Object> chartData = new HashMap<>();
            chartData.put("labels", labels);
            List<Map<String, Object>> datasets = new ArrayList<>();
            Map<String, Object> dataset = new HashMap<>();
            dataset.put("label", "Dataset 1"); // 可以根据需要更改
            dataset.put("data", data);
            // 如果需要，可以添加其他属性，如backgroundColor
            datasets.add(dataset);
            chartData.put("datasets", datasets);

            // 将chartData转换为JSON字符串
            String jsonString = objectMapper.writeValueAsString(chartData);

            // 设置响应的内容类型和字符编码
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");

            // 写入JSON数据到响应
            try (PrintWriter out = response.getWriter()) {
                out.print(jsonString);
            }
        } catch (SQLException e) {
            // 处理SQLException，并返回一个错误响应给客户端
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            try (PrintWriter out = response.getWriter()) {
                // 创建一个简单的错误响应对象，例如：{"error": "Database error"}
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("error", "Database error");
                String errorJson = objectMapper.writeValueAsString(errorResponse);
                out.print(errorJson);
            }
        }
    }
}